package sctu;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/30.
 */
public class DataBase {

    public List<User> getUserList(){

        List<User> userList = new ArrayList<User>();

        //3+1
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;

            String sql = "select * from t_users";
            //需要记住
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/sctu_javaweb_2018?serverTimezone=UTC",
                    "root",
                    "123456");
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            //遍历resultSet这个对象
            while (resultSet.next()){
                int id = resultSet.getInt(1);
                String username = resultSet.getString(2);
                String password = resultSet.getString(3);
                //封装user类进入userlist
                User user = new User();
                user.setId(id);
                user.setUsername(username);
                user.setPassword(password);

                userList.add(user);
            }
            //记得关闭
            resultSet.close();
            statement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;
    }
}
